<?php
/**
 * Created by PhpStorm.
 * User: 黑盒子
 * Date: 2020/11/16
 * Time: 21:11
 */

namespace app\api\controller;

use app\common\exception\ApiException;

class Type extends Base
{
    public function add()
    {
        $name = input('name');

        if (!$name) {
            throw new ApiException(['msg' => '名称不能为空']);
        }

        $exist = \app\api\model\Type::where('name',$name)->where('is_delete',0)->find();

        if ($exist) {
            throw new ApiException(['msg' => '该类型已存在']);
        }

        $type = \app\api\model\Type::create(['name' => $name]);

        if (!$type->id) {
            throw new ApiException(['msg' => '操作失败']);
        }

        return json(['success' => 1, 'msg' => '新增成功']);
    }

    public function listing()
    {
        $__page_size = input('__page_size',10);
        $list = \app\api\model\Type::where('is_delete',0)
            ->order('id desc')
            ->field('id,name');

        if ($__page_size) {
            $list = $list->paginate($__page_size);
        } else {
            $list = $list->select();
        }

        return json(['success' => 1, 'list' => $list]);
    }

    public function delete()
    {
        $id = input('id');

        if ($id) {
            $exist = \app\api\model\Type::where('is_delete', 0)->where('id', $id)->find();

            if (!$exist) {
                throw new ApiException(['msg' => '该类型不存在或已被删除']);
            }

            $rst = \app\api\model\Type::update(['is_delete' => 1], ['id' => $id]);
            if (!$rst) {
                throw new ApiException(['msg' => '操作失败']);
            }
        } else {
            throw new ApiException(['msg' => '参数错误']);
        }

        return json(['success' => 1, 'msg' => '操作成功']);
    }

    public function edit()
    {
        $id = input('id');
        $name = input('name');

        if ($id) {
            $exist = \app\api\model\Type::where('is_delete', 0)->where('id', $id)->find();

            if (!$exist) {
                throw new ApiException(['msg' => '该类型不存在或已被删除']);
            }

            $rst = \app\api\model\Type::update(['name' => $name], ['id' => $id]);
            if (!$rst) {
                throw new ApiException(['msg' => '操作失败']);
            }
        } else {
            throw new ApiException(['msg' => '参数错误']);
        }

        return json(['success' => 1, 'msg' => '操作成功']);
    }
}